<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/25
 * Time: 14:19
 */

namespace app\qgroup\service;


use app\common\Enum\CommonEnum;
use app\common\service\BaseService;
use app\qgroup\model\GroupList;
use app\qgroup\model\GroupMemberMapping;
use app\qgroup\model\QqCodeMapping;
use think\Exception;
use think\Model;

class ConfigService extends BaseService
{
    /**
     * 初始化一个QQ信息
     * @param $qq string|int QQ号
     * @param $groups array QQ群号
     * @param array &$existQgroup 已存在的QQ群号
     * @return QqCodeMapping QQ基本信息
     * @throws \think\exception\DbException
     */
    public static function init($qq,$groups,&$existQgroup = [])
    {
        $cf = CodeFactory::getInstance();
        $code = $cf->getNewCode($qq);
        $qcm = QqCodeMapping::create([
            'qq'=>$qq
            ,'code'=>$code
            ,'status'=>CommonEnum::COMMON_VALID
            ,'activation_status'=>CommonEnum::COMMON_INVALID
            ,'pay_status'=>CommonEnum::COMMON_INVALID
        ]);
        foreach ($groups as $group){
            $gl = GroupList::get(['group'=>$group]);
            if (!$gl){              #不存在数据，补充数据
                GroupList::create([
                    'qq'=>$qq
                    ,'group'=>$group
                    ,'status'=>CommonEnum::COMMON_VALID
                ]);
            } elseif ($gl->qq == $qq){      #存在且是同一QQ号，跳过
                continue;
            } elseif ($gl->qq != $qq){      #存在，且不是同一QQ号，记录
                $existQgroup[] = $group;
            }
        }
        return $qcm;
    }

    /**
     * @param $gl GroupList
     * @param $qqInfo array
     * @return GroupMemberMapping|null
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public static function createQqGroupMapping($gl,$qqInfo)
    {
        $qqInfo['entering_group_time'] = date('Y-m-d H:i:s',$qqInfo['entering_group_time']);
        $gmm = GroupMemberMapping::get(['group_list_id'=>$gl->id,'qq'=>$qqInfo['QQ']]);
        if (!$gmm) {
            return GroupMemberMapping::create([
                'group_list_id' => $gl->id
                , 'qq' => $qqInfo['QQ']
                , 'nickname' => $qqInfo['nickname']
                , 'sex' => $qqInfo['sex']
                , 'age' => $qqInfo['age']
                , 'area' => $qqInfo['area']
                , 'entering_group_time' =>$qqInfo['entering_group_time']
                , 'administrative_authority' => $qqInfo['administrative_authority']
            ]);
        }
        if ($gmm->status == 30){
            throw new Exception('此用户被踢出，无法添加');
        }
        $r = $gmm->save(array_merge($qqInfo,['status'=>99]));
        return $gmm;
    }
}